//
//  SCBannerView.m
//  SCFoundationKit
//
//  Created by Chao Sheng on 2023/10/16.
//

#import "SCBannerView.h"
#import "SCBasicKit.h"

@interface SCBannerView ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIPageControl *pageControl;
/// 轮播定时器
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation SCBannerView {
    NSMutableArray *_finalImages;
    CGFloat _banner_width;
    CGFloat _banner_height;
    NSMutableArray *_imgViewArr;
}

- (instancetype)init {
    if(self = [super init]) {
        self.carouselDuration = 5;
        self.isZoom = true;
        self.backgroundColor = UIColor.clearColor;
    }
    return self;
}

- (void)setImageNames:(NSArray *)imageNames {
    _imageNames = imageNames;
}

- (void)setImageURLNames:(NSArray *)imageURLNames {
    _imageURLNames = imageURLNames;
}

- (void)setBannerSize:(CGSize)bannerSize {
    _bannerSize = bannerSize;
}

- (void)reload {
    
    if(_finalImages.count >0) {
        [self removeImage];
    }
    
    [self setupImage];
}

- (void)removeImage {
    [self.scrollView removeFromSuperview];
    self.scrollView = nil;
    
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)setupImage{
    
    _banner_width =  _bannerSize.width;
    _banner_height = _bannerSize.height;

    [self addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.top.bottom.equalTo(@0);
        make.width.equalTo(@(self->_banner_width));
    }];
   
    NSArray *images = _imageNames.count > 0 ? _imageNames : _imageURLNames;
    BOOL isNetworkImage = _imageNames.count > 0 ? false : true;
    NSMutableArray *finalImages = [NSMutableArray arrayWithArray:images];
    _finalImages = finalImages;
    if(images.count > 1) {
        [finalImages insertObject:images.lastObject atIndex:0];
        [finalImages insertObject:images.firstObject atIndex:finalImages.count];
    }
    [self addSubview:self.scrollView];
    
    _imgViewArr = @[].mutableCopy;
    /// 首尾增加一张图片，实现无限轮播
    for(NSInteger i = 0; i < finalImages.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * _banner_width, 0, _banner_width, _banner_height)];
        if(isNetworkImage) {
            NSString *name = [finalImages[i] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [imageView sd_setImageWithURL:[NSURL URLWithString:name] placeholderImage:[UIImage imageNamed:@"sc_banner"]];
        } else {
            imageView.image = [UIImage imageNamed:finalImages[i]];
        }

        imageView.tag = i + 1000;
        imageView.layer.cornerRadius = 8;
        imageView.layer.masksToBounds = true;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [self.scrollView addSubview:imageView];
        [_imgViewArr addObject:imageView];
    }
    self.scrollView.contentSize = CGSizeMake(_banner_width * finalImages.count, 0);
    
    [self addSubview:self.pageControl];
    self.pageControl.currentPage = 0;
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@-12);
        make.height.equalTo(@10);
        make.centerX.equalTo(@0);
    }];
    
    if(images.count == 1) {
        self.pageControl.hidden = true;
        UIImageView *imageV = _imgViewArr.firstObject;
        imageV.frame = CGRectMake(0, 0,sc_screen_width,_banner_height);
    } else if (images.count > 7) {
        self.pageControl.hidden = true;
    } else {
        self.pageControl.hidden = false;
    }
    self.pageControl.numberOfPages = images.count;
    
    if(_isCarousel) {
        [self setupTimer];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if(_imgViewArr.count > 1) {
        [self.scrollView setContentOffset:CGPointMake(_banner_width, 0)];
    }
}

- (void)carouselPause {
    if(self.timer) {
        [self.timer setFireDate:[NSDate distantFuture]];
    }
}

- (void)carouselContinue {
    [self setupTimer];
}

#pragma mark - 轮播定时器
- (void)setupTimer {
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    __weak typeof(self) weakSelf = self;
    if (@available(iOS 10.0, *)) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0f repeats:NO block:^(NSTimer * _Nonnull timer) {
            weakSelf.pageNum = weakSelf.pageNum + 1;
            CGFloat offset = weakSelf.pageNum * self->_banner_width;
            [weakSelf.scrollView setContentOffset:CGPointMake(offset, 0) animated:true];
        }];
    } else {
        // Fallback on earlier versions
        self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:[self sc_selecorBlock:^(id time) {
            weakSelf.pageNum = weakSelf.pageNum + 1;
            CGFloat offset = weakSelf.pageNum * self->_banner_width;
            [weakSelf.scrollView setContentOffset:CGPointMake(offset, 0) animated:true];
        }] userInfo:nil repeats:NO];
    }
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

#pragma mark - 懒加载
- (UIScrollView *)scrollView {
    if(!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = true;
        _scrollView.showsHorizontalScrollIndicator = false;
//        _scrollView.bounces = false;
        _scrollView.clipsToBounds = false; //显示出左右区域
    }
    return _scrollView;
}

- (UIPageControl *)pageControl {
    if(!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        [_pageControl setCurrentPageIndicatorTintColor:UIColor.whiteColor];
        [_pageControl setPageIndicatorTintColor:sc_grayColor];
        _pageControl.userInteractionEnabled = false;
    }
    return _pageControl;
}

#pragma mark - delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger pageNum = scrollView.contentOffset.x / _banner_width;
    self.pageNum = pageNum;
    if(_isZoom) {
        [self setScrollContentZoom:scrollView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger pageNum = scrollView.contentOffset.x / _banner_width;
    self.pageNum = pageNum;
    NSInteger currentPage = pageNum;
    CGFloat offset = 0;
    if (pageNum == 0) {
        offset = _banner_width * (_finalImages.count - 2);
        currentPage = _finalImages.count-3;
        [self.scrollView setContentOffset:CGPointMake(offset, 0)];
    } else if (pageNum == _finalImages.count - 1) {
        offset = _banner_width ;
        currentPage = 0;
        [self.scrollView setContentOffset:CGPointMake(offset, 0)];
    } else {
        currentPage = pageNum - 1;
    }
       
    self.pageControl.currentPage = currentPage;
}

/// 手动拖动时，定时器结束
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if(self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

/// 结束拖动，定时器开启
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self setupTimer];
}

/// 定时器滑动结束动画
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    NSInteger pageNum = scrollView.contentOffset.x / _banner_width;
    self.pageNum = pageNum;
    NSInteger currentPage = pageNum;
    CGFloat offset = 0;
    if (pageNum == 0) {
        offset = _banner_width * (_finalImages.count - 2);
        currentPage = _finalImages.count-3;
        [self.scrollView setContentOffset:CGPointMake(offset, 0)];
    } else if (pageNum == _finalImages.count - 1) {
        offset = _banner_width ;
        currentPage = 0;
        [self.scrollView setContentOffset:CGPointMake(offset, 0)];
    } else {
        currentPage = pageNum - 1;
    }
       
    self.pageControl.currentPage = currentPage;
    
    [self setupTimer];
}

/// 对图片进行缩放的方法
- (void)setScrollContentZoom:(UIScrollView*)scrollView {
    CGFloat centerx = scrollView.contentOffset.x + scrollView.bounds.size.width * 0.5;
    for (UIImageView *imagev in _imgViewArr) {
        //计算当前控件与显示区中心点的相对距离
        CGFloat distance = ABS(imagev.center.x - centerx);
        //设置缩放系数
        CGFloat factor= 0.0002;
        //获取缩放倍数
        CGFloat scales= 1 / (1+distance*factor);
//        NSLog(@"%.1f",scales);
        //进行缩放
        imagev.transform = CGAffineTransformMakeScale(scales, scales);
    }
}




@end
